package top.frsf.pattern.a_creational.b_factory.a_simple_factory;

import top.frsf.pattern.a_creational.b_factory.a_simple_factory.service.Payment;
import top.frsf.pattern.a_creational.b_factory.a_simple_factory.service.impl.*;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Supplier;

/**
 * 简单工厂模式 - 非单例
 *
 * @author He Kuntao
 * @since 2025/4/22 15:04
 */
public class PaymentFactory {
    /**
     * 支付类型与支付对象构造器映射
     */
    private static final Map<String, Supplier<Payment>> CONSTRUCTORS = new ConcurrentHashMap<>();

    static {
        registerPayment("app", AppPayment::new);
        registerPayment("vx", VxPayment::new);
        registerPayment("zfb", ZfbPayment::new);
    }

    /**
     * 注册支付类型
     *
     * @param type      支付类型
     * @param constructor 支付对象构造器
     */
    public static void registerPayment(String type, Supplier<Payment> constructor) {
        CONSTRUCTORS.put(type, constructor);
    }

    /**
     * 根据类型创建支付对象
     *
     * @param type 支付类型
     * @return 支付对象
     */
    public static Payment createPayment(String type) {
        Supplier<Payment> constructor = CONSTRUCTORS.get(type);
        if (constructor == null) {
            throw new IllegalArgumentException("Unknown payment type: " + type);
        }
        return constructor.get();
    }
}